<?php

namespace lxs\tools;

use App\Models\users\UsersListModel;
use Illuminate\Support\Facades\Redis;

class AuthToken
{

    protected $token = null;
    protected $uid = null;
    protected $module = null;

    public function __construct($module = 'api')
    {
        $this->module = $module;
    }


    public function getToken()
    {
        if (!$this->token) {
            $this->token = request()->header('authorization');
        }
        return $this->token;
    }


    public function setToken($token)
    {
        $this->token = $token;
    }


    public function checkToken(): bool
    {
        if (!$this->token) {
            $this->token = request()->header('authorization');
        }
        if (!$this->token) {
            $this->token = request()->input('token');
        }

        $uid = Redis::get($this->token);
        if ($uid) {
            $this->uid = $uid;
        }
        return !!$uid;
    }


    public function createToken($uid)
    {
        $token = uniqid(32);
        Redis::setEx($token, 86400 * 30, $uid);
        return $token;
    }


    public function getUid()
    {
        if (!$this->uid) {
            $this->uid = Redis::get($this->getToken());
        }
        return $this->uid;
    }


    public function destroyToken()
    {
        if ($this->token) {
            Redis::del($this->token);
        }
    }


}
